package com.lc.service.impl;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.guigu.mapper.*;
import com.guigu.pojo.*;
import com.lc.service.TmenberService;
import com.lc.util.Getserial;
import com.lc.vo.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class TmenberServiceimpl implements TmenberService {

    @Resource
    private TMemberMapper tMemberMapper;

    @Resource
    private TMemberInfoMapper tMemberInfoMapper;

    @Resource
    private THealthmgrMapper tHealthmgrMapper;

    @Resource
    private Getserial getserial;

    @Resource
    private TMemberDynamicinfoMapper tMemberDynamicinfoMapper;

    @Resource
    private TMemberMedicalhistoryMapper tMemberMedicalhistoryMapper;

    @Resource
    private  TMemberExaminationMapper tMemberExaminationMapper;

    @Resource
    private TOrdersettingMapper tOrdersettingMapper;

    @Resource
    private TMemberStatisticsMapper tMemberStatisticsMapper;

    @Resource
    private TSetmealMapper setmealMapper;

    @Resource
    private  TExaminationMapper tExaminationMapper;

    @Resource
    private TUserMapper tUserMapper;

    @Override
    public PageInfo<Tmenberview> selectmenberpageService(pageVo<Tmenberview> vo) {
        //分页
        PageHelper.startPage(vo.getPageNum(),vo.getPageSize());
        PageInfo<Tmenberview> page=new PageInfo<Tmenberview>(this.tMemberMapper.selectmenberpage(vo.getPagedata()));
        System.out.println(this.tMemberMapper.selectmenberpage(vo.getPagedata()));
        return page;
    }

    @Override
    public void deletePhysicalBytmenberidService(int id,int status) {
        //禁用或者启用
       if(status==1){
           this.tMemberInfoMapper.deletePhysicalBytmenberid(id);
       }else{
           this.tMemberInfoMapper.deletePhysicalBytmenberid1(id);
       }
    }

    @Override
    public List<TUser> queryallthealthmgrsEervice() {
        //健康管理师
        System.out.println(this.tHealthmgrMapper.queryallthealthmgr());
//        return this.tHealthmgrMapper.queryallthealthmgr();
        return this.tUserMapper.queryallstatus0();

    }

    @Override
    public void addtmemberService(Tmenberview tmenberview) {
        //添加会员档案
        tmenberview.setFilenumber(this.getserial.returnId());
        this.tMemberMapper.inserttmenber(tmenberview);
        //添加会员信息表
        int querymaxtmemberbyid = this.tMemberMapper.querymaxtmemberbyid();
        tmenberview.setTMemberId(querymaxtmemberbyid);
        this.tMemberInfoMapper.inserttmemberinfo(tmenberview);
        //添加会员动态信息表
        this.tMemberDynamicinfoMapper.insertmemberdynamicinfo(tmenberview);
        //添加病史
        this.tMemberMedicalhistoryMapper.insertmembermedicalhistory(tmenberview);

        Date date = new Date();
        SimpleDateFormat dtf = new SimpleDateFormat("yyyy-MM-dd");
        String last_time = dtf.format(date);
        TMemberStatistics querydatememberstatistics = this.tMemberStatisticsMapper.querydatememberstatistics(last_time);
        if(querydatememberstatistics!=null){
            this.tMemberStatisticsMapper.updatedatememberstiticsmember(last_time);
        }else{
            this.tMemberStatisticsMapper.insertmemberstitcs(last_time);
            this.tMemberStatisticsMapper.updatedatememberstiticsmember(last_time);

        }


    }

    @Override
    public void updatetmenberService(Tmenberview tmenberview) {
        //修改会员档案
        this.tMemberMapper.updatetmenber(tmenberview);
        this.tMemberInfoMapper.updatetmemberinfoBYtMemberId(tmenberview);
        this.tMemberDynamicinfoMapper.updatememberdynamicinfoBYtmenuid(tmenberview);
        this.tMemberMedicalhistoryMapper.updatetmembermedicalhistoryBYtemnberid(tmenberview);

    }

    @Override
    public PageInfo<TmemberexaminsetmealView> selecttmenmberexamin(pageVo<TmemberexaminsetmealView> pageVo) {
        PageHelper.startPage(pageVo.getPageNum(),pageVo.getPageSize());
        PageInfo info=new PageInfo(this.tMemberExaminationMapper.selectTmemberexaminsetmealallpage((pageVo.getPagedata())));
        return info;
    }

    @Override
    public querystatisticsView querystatisticsService(querystatisticsView view) {
        //预约人数
        view.setTordersettingstart(view.getZ().get(0));
        view.setTordersettingend(view.getZ().get(1));
        List<TOrdersetting> querysettingfangwei = this.tOrdersettingMapper.querysettingfangwei(view);
        view.setTordersettingList(querysettingfangwei);

        //查询登录次数和新增会员次数
        List<TMemberStatistics> querytmemberstatistics = this.tMemberStatisticsMapper.querytmemberstatistics(view);
        view.setTmemberstatistics(querytmemberstatistics);
        return view;
    }

    @Override
    public int addmemberexaminService(TMemberExamination tMemberExamination) {
        this.tMemberExaminationMapper.inserttmemberstitcs(tMemberExamination);
        return 0;
    }

    @Override
    public List<TSetmeal> querysetmealname(TSetmeal tSetmeal) {
            return this.setmealMapper.querysetmeal(tSetmeal);

    }

    @Override
    public int schuanmemberexaminService(ExaminView view) {
        this.tExaminationMapper.insertpiliangByid(view);
        //修改状态为一上传
        this.tMemberExaminationMapper.updatememberexsticsestatsby2(view.getZid());
        return 0;
    }

    @Override
    public int huoquyanzhengmaService(String phone) {
        String testUsername = "2830756158"; //在短信宝注册的用户名
        String testPassword = "lichao001"; //在短信宝注册的密码
        String testPhone = phone;
       int yanzm=(int)((Math.random()*9+1)*1000);
        String testContent = "【万千购】您的验证码是:"+yanzm+",30分钟内有效。若非本人操作请忽略此消息。"; // 注意测试时，也请带上公司简称或网站签名，发送正规内容短信。千万不要发送无意义的内容：例如 测一下、您好。否则可能会收不到

        String httpUrl = "http://api.smsbao.com/sms";

        StringBuffer httpArg = new StringBuffer();
        httpArg.append("u=").append(testUsername).append("&");
        httpArg.append("p=").append(md5(testPassword)).append("&");
        httpArg.append("m=").append(testPhone).append("&");
        httpArg.append("c=").append(encodeUrlString(testContent, "UTF-8"));

        String result = request(httpUrl, httpArg.toString());
        System.out.println(result);
        return yanzm;
    }

    @Override
    public int deletememberService(int id) {
        this.tMemberMapper.deleteByPrimaryKey(id);
        this.tMemberDynamicinfoMapper.deletememberid(id);
        this.tMemberInfoMapper.deletememberid(id);
        return 1;
    }

    @Override
    public int deletemembererxamin(int id) {
        this.tMemberExaminationMapper.deleteByPrimaryKey(id);
        this.tExaminationMapper.deletememberid(id);
        return 1;
    }


    public static String request(String httpUrl, String httpArg) {
        BufferedReader reader = null;
        String result = null;
        StringBuffer sbf = new StringBuffer();
        httpUrl = httpUrl + "?" + httpArg;

        try {
            URL url = new URL(httpUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            InputStream is = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String strRead = reader.readLine();
            if (strRead != null) {
                sbf.append(strRead);
                while ((strRead = reader.readLine()) != null) {
                    sbf.append("\n");
                    sbf.append(strRead);
                }
            }
            reader.close();
            result = sbf.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static String md5(String plainText) {
        StringBuffer buf = null;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(plainText.getBytes());
            byte b[] = md.digest();
            int i;
            buf = new StringBuffer("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return buf.toString();
    }

    public static String encodeUrlString(String str, String charset) {
        String strret = null;
        if (str == null)
            return str;
        try {
            strret = java.net.URLEncoder.encode(str, charset);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return strret;
    }
}
